<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { register } from '@/api/auth.js'
import { getAllColleges, getAllMajors, getAllClasses } from '@/api/school'

const formRef = ref()
const loading = ref(false)

const formData = ref({
  // 个人信息
  username: '',
  password: '',
  name: '',
  gender: '',
  birthDate: '',
  studentId: '',

  // 校友信息
  enrollYear: null,
  graduateYear: null,
  collegeCode: '',
  majorCode: '',
  classCode: '',

  // 当前情况
  mobile: '',
  email: '',
  industry: '',
  workUnit: ''
})

// 学校信息选项
const colleges = ref([])
const majors = ref([])
const classes = ref([])

// 加载学院列表
const loadColleges = async () => {
  try {
    const res = await getAllColleges()
    if (res.code === 200) {
      colleges.value = res.data.map(college => ({
        value: college.collegeCode,
        label: college.currentName || college.historyName
      }))
    }
  } catch (error) {
    ElMessage.error('获取学院列表失败')
  }
}

// 加载专业列表
const loadMajors = async () => {
  try {
    const res = await getAllMajors()
    if (res.code === 200) {
      majors.value = res.data.map(major => ({
        value: major.majorCode,
        label: major.currentName || major.historyName
      }))
    }
  } catch (error) {
    ElMessage.error('获取专业列表失败')
  }
}

// 加载班级列表
const loadClasses = async () => {
  try {
    const res = await getAllClasses()
    if (res.code === 200) {
      classes.value = res.data.map(cls => ({
        value: cls.classCode,
        label: cls.classCode
      }))
    }
  } catch (error) {
    ElMessage.error('获取班级列表失败')
  }
}

// 页面加载时获取所有数据
onMounted(() => {
  loadColleges()
  loadMajors()
  loadClasses()
})

// 年份验证
const validateYear = (rule, value, callback) => {
  if (value < 1900 || value > new Date().getFullYear() + 1) {
    callback(new Error('请输入有效年份'))
  } else {
    callback()
  }
}

// 毕业年份验证
const validateGraduateYear = (rule, value, callback) => {
  if (!value) {
    callback()
    return
  }
  if (value <= formData.value.enrollYear) {
    callback(new Error('毕业年份必须大于入学年份'))
  } else {
    callback()
  }
}

const submitForm = async () => {
  try {
    loading.value = true
    await formRef.value.validate()

    // 数据转换处理
    const submitData = {
      ...formData.value,
      // 确保数字类型正确
      enrollYear: Number(formData.value.enrollYear),
      graduateYear: formData.value.graduateYear ?
        Number(formData.value.graduateYear) : null,
      // 性别字段适配后端枚举值（根据实际情况调整）
      gender: formData.value.gender === '男' ? '男' : '女'
    }

    // 调用注册接口
    const response = await register(submitData)

    if (response.code === 200) {
      ElMessage.success('注册成功')
      // 跳转登录页
      setTimeout(() => {
        window.location.href = '/login'
      }, 1500)
    } else {
      ElMessage.error(response.msg || '注册失败')
    }
  } catch (error) {
    // 错误处理
    if (error.response) {
      const msg = error.response.data.msg || '请求错误'
      ElMessage.error(msg)
    } else {
      ElMessage.error('请求失败：' + error.message)
    }
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="register-container">
    <div class="register-box">
      <h2 class="title">用户注册</h2>

      <el-form
        ref="formRef"
        :model="formData"
        label-width="100px"
        label-position="top"
      >
        <!-- 个人信息模块 -->
        <el-card class="form-section">
          <template #header>
            <div class="section-title">个人信息（必填）</div>
          </template>

          <el-form-item
            label="用户名"
            prop="username"
            :rules="[{ required: true, message: '用户名不能为空' }]"
          >
            <el-input v-model="formData.username" />
          </el-form-item>

          <el-form-item
            label="密码"
            prop="password"
            :rules="[{ required: true, message: '密码不能为空' }, { min: 6, message: '密码至少6位' }]"
          >
            <el-input v-model="formData.password" type="password" show-password />
          </el-form-item>

          <el-form-item
            label="姓名"
            prop="name"
            :rules="[{ required: true, message: '姓名不能为空' }]"
          >
            <el-input v-model="formData.name" />
          </el-form-item>

          <el-form-item label="性别">
            <el-select v-model="formData.gender">
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>

          <el-form-item label="出生日期">
            <el-date-picker
              v-model="formData.birthDate"
              type="date"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>

          <el-form-item
            label="学号"
            prop="studentId"
            :rules="[{ required: true, message: '学号不能为空' }]"
          >
            <el-input v-model="formData.studentId" />
          </el-form-item>
        </el-card>

        <!-- 校友信息模块 -->
        <el-card class="form-section">
          <template #header>
            <div class="section-title">校友信息（必填）</div>
          </template>

          <el-form-item
            label="入学年份"
            prop="enrollYear"
            :rules="[
              { required: true, message: '入学年份不能为空' },
              { type: 'number', message: '必须为数字', trigger: 'blur' },
              { validator: validateYear }
            ]"
          >
            <el-input v-model.number="formData.enrollYear" />
          </el-form-item>

          <el-form-item
            label="毕业年份"
            prop="graduateYear"
            :rules="[
              { type: 'number', message: '必须为数字', trigger: 'blur' },
              { validator: validateGraduateYear }
            ]"
          >
            <el-input v-model.number="formData.graduateYear" />
          </el-form-item>

          <el-form-item
            label="学院"
            prop="collegeCode"
            :rules="[{ required: true, message: '请选择学院' }]"
          >
            <el-select
              v-model="formData.collegeCode"
              placeholder="请选择学院"
            >
              <el-option
                v-for="item in colleges"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="专业"
            prop="majorCode"
            :rules="[{ required: true, message: '请选择专业' }]"
          >
            <el-select
              v-model="formData.majorCode"
              placeholder="请选择专业"
            >
              <el-option
                v-for="item in majors"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="班级"
            prop="classCode"
            :rules="[{ required: true, message: '请选择班级' }]"
          >
            <el-select
              v-model="formData.classCode"
              placeholder="请选择班级"
            >
              <el-option
                v-for="item in classes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-card>

        <!-- 当前情况模块 -->
        <el-card class="form-section">
          <template #header>
            <div class="section-title">当前情况（选填）</div>
          </template>

          <el-form-item
            label="手机号"
            prop="mobile"
            :rules="[{ len: 11, message: '手机号必须为11位' }]"
          >
            <el-input v-model="formData.mobile" />
          </el-form-item>

          <el-form-item label="邮箱" prop="email" :rules="[{ type: 'email', message: '邮箱格式不正确' }]">
            <el-input v-model="formData.email" />
          </el-form-item>

          <el-form-item label="所属行业">
            <el-input v-model="formData.industry" />
          </el-form-item>

          <el-form-item label="工作单位">
            <el-input v-model="formData.workUnit" />
          </el-form-item>
        </el-card>

        <div class="action-buttons">
          <el-button
            type="primary"
            @click="submitForm"
            :loading="loading"
          >
            {{ loading ? '提交中...' : '立即注册' }}
          </el-button>
          <el-button @click="$router.push('/login')">返回登录</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.register-container {
  padding: 20px;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.register-box {
  max-width: 800px;
  margin: 0 auto;
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.form-section {
  margin-bottom: 20px;
}

.section-title {
  font-weight: bold;
  color: #409eff;
}

:deep(.el-form-item__label) {
  font-weight: bold;
}

.action-buttons {
  text-align: center;
  margin-top: 30px;
}

.el-button {
  width: 150px;
  height: 40px;
  margin: 0 10px;
}

:deep(.el-input__inner) {
  height: 40px;
}
</style>
